package com.mvc.controller.skdata;

import java.io.BufferedReader;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.huangqj.classification.Pressure;
import org.huangqj.classification.Sugar;
import org.huangqj.consant.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mvc.framework.constant.GlobalConstant;
import com.mvc.model.base.Json;
import com.mvc.model.healthmanager.archive.Electrocardio;
import com.mvc.model.healthmanager.archive.Temperature;
import com.mvc.model.healthmanager.archive.Urine;
import com.mvc.model.mb.archive.BaseInfo;
import com.mvc.model.report.ColligateReport;
import com.mvc.model.vo.HealthBlood;
import com.mvc.model.vo.HealthFat;
import com.mvc.model.vo.HealthLink;
import com.mvc.model.vo.HealthPressure;
import com.mvc.model.vo.HealthSugar;
import com.mvc.model.vo.HealthWeight;
import com.mvc.model.vo.SonkaData;
import com.mvc.model.vo.e100.v2.E100AllData;
import com.mvc.service.healthmanager.UrineServiceI;
import com.mvc.service.vo.BaseInfoService;
import com.mvc.service.vo.ColligateReportService;
import com.mvc.service.vo.ElectrocardioServiceI;
import com.mvc.service.vo.GetSonkaDataService;
import com.mvc.service.vo.HealthBloodService;
import com.mvc.service.vo.HealthFatService;
import com.mvc.service.vo.HealthLinkService;
import com.mvc.service.vo.HealthPressureService;
import com.mvc.service.vo.HealthSugarService;
import com.mvc.service.vo.HealthWeightService;
import com.mvc.service.vo.SkDataService;
import com.mvc.service.vo.TemperatureServiceI;
import com.mvc.service.vo.impl.CustomService;
import com.mvc.utils.StringUtil;

/**
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2015年9月14日 下午6:35:42 <br/>
 * @author qingjie
 *
 */
@Controller
@RequestMapping("/base")
public class SkDataController {
	
	/**
	 * service的注入
	 */
	@Autowired
	private BaseInfoService bInfoService;
	@Autowired
	private GetSonkaDataService gDataService;
	@Autowired
	private HealthFatService hFatService;
	@Autowired
	private HealthPressureService hPressureService;
	@Autowired
	private HealthSugarService hSugarService;
	@Autowired
	private HealthWeightService hWeightService;
	@Autowired
	private HealthBloodService hBloodService;
	@Autowired
	private HealthLinkService hLinkService;
	@Autowired
	private ElectrocardioServiceI eService;
	@Autowired
	private TemperatureServiceI tService;
	@Autowired
	private CustomService cService;
	@Autowired
	private SkDataService sds;
	@Autowired
	private ColligateReportService crs;
	@Autowired
	private UrineServiceI usi;
	
	private boolean returnValue = false;
	private String personId;
	private Boolean bl = false;
	
	
	/**
	 * 根据idCard查询系统是否存在用户档案，若不存在则自动建档，并返回档案id,且进行血糖/血压/脂肪等信息的添加
	 * @param request
	 * @param response
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping("/select.do")
	@ResponseBody
	public boolean select(HttpServletRequest request, HttpServletResponse response)  
			throws Exception{
		request.setCharacterEncoding("utf-8");
		//获取request传输过来的字符流
		BufferedReader bf = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line;
		//循环读取字符流所有字符添加到 sb 可变字符串
		while((line=bf.readLine())!=null){
			sb.append(line);
		}
		String json = sb.toString();
		System.out.println("未转化数据："+json);
		json = URLDecoder.decode(json,"utf-8");
		String[] s = json.split("=");
		if(s.length>1){
			json = s[1];
		}
		System.out.println("已转化数据："+json);
		//判断是否 正常传值
		if(json.isEmpty()){
			//false表示失败；true表示成功
			returnValue = false;
		}else{
			SonkaData sData = gDataService.getData(json);
			//获取用户基本数据
			BaseInfo baseInfo = gDataService.returnObject(sData, BaseInfo.class, 1);
			//获取脂肪信息
			HealthFat hFat = gDataService.returnObject(sData, HealthFat.class, 2);
			//获取血压信息
			HealthPressure hPressure = gDataService.returnObject(sData, HealthPressure.class, 3);
			//获取血糖信息
			HealthSugar hSugar = gDataService.returnObject(sData, HealthSugar.class, 4);
			//获取体重
			HealthWeight hweight = gDataService.returnObject(sData, HealthWeight.class, 5);
			//获取血氧
			HealthBlood hBlood = gDataService.returnObject(sData, HealthBlood.class, 6);
			//获取心电
			HealthLink hLink = gDataService.returnObject(sData, HealthLink.class, 7);
			//心电图
			Electrocardio ecg = gDataService.returnObject(sData, Electrocardio.class, 8);
			//体温
			Temperature temperature = gDataService.returnObject(sData, Temperature.class, 9);
			
			bl = saveData(baseInfo, hFat, hPressure, hSugar, hweight, hBlood, hLink, ecg,temperature,new Urine(),new ColligateReport());
			if(bl){
				returnValue = true;
			}
		}
		return returnValue;
		
	}
	
	/**
	 * 双佳一体机接口
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getR100Data.do")
	@ResponseBody
	public int getR100Data(HttpServletRequest request) throws Exception{
		int returnValue = 1;
		request.setCharacterEncoding("utf-8");
		//获取request传输过来的字符流
		BufferedReader bf = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line;
		//循环读取字符流所有字符添加到 sb可变字符串
		while((line=bf.readLine())!=null){
			sb.append(line);
		}
		String json = sb.toString();
		System.out.println("未转化数据："+json);
		//乱码处理
		//json = new String(json.getBytes("iso-8859-1"),"utf-8");
//		String[] s = json.split("=");
//		if(s.length>1){
//			json = s[1];
//		}
		json = URLDecoder.decode(json,"utf-8");
		System.out.println("已转化数据："+json);
		//判断是否 正常传值
		if(json.isEmpty()){
			//1表示失败；0表示成功
			return returnValue ;
		}else{
		
			SonkaData sData = gDataService.getData(json);
			//获取用户基本数据
			BaseInfo baseInfo = gDataService.returnR100Data(sData, BaseInfo.class, 1);
			sData.setBranchno(baseInfo.getCreatfileDepId());
			//获取脂肪信息
			HealthFat hFat = gDataService.returnR100Data(sData, HealthFat.class, 2);
			//获取血压信息
			HealthPressure hPressure = gDataService.returnR100Data(sData, HealthPressure.class, 3);
			//获取血糖信息
			HealthSugar hSugar = gDataService.returnR100Data(sData, HealthSugar.class, 4);
			//获取体重
			HealthWeight hweight = gDataService.returnR100Data(sData, HealthWeight.class, 5);
			//获取血氧
			HealthBlood hBlood = gDataService.returnR100Data(sData, HealthBlood.class, 6);
			//获取心电
			HealthLink hLink = gDataService.returnR100Data(sData, HealthLink.class, 7);
			//心电图
			Electrocardio ecg = gDataService.returnR100Data(sData, Electrocardio.class, 8);
			//体温
			Temperature temperature = gDataService.returnR100Data(sData, Temperature.class, 9);
			//
			if(!ValidatorUtil.isBlankOnString(sData.getIdCode())){
				bl = saveData(baseInfo, hFat, hPressure, hSugar, hweight, hBlood, hLink, ecg, temperature,new Urine(),new ColligateReport());
			}
			if(bl){
				returnValue = 0;
			}
			
		}
		return returnValue;
	}
	
	@RequestMapping("/getMobileData.do")
	@ResponseBody
	public Boolean getDataByMobile(HttpServletRequest request)throws Exception{
		request.setCharacterEncoding("gbk");
		//获取request传输过来的字符流
		BufferedReader bf = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line;
		//循环读取字符流所有字符添加到 sb 可变字符串
		while((line=bf.readLine())!=null){
			sb.append(line);
		}
		String json = sb.toString();
		System.out.println("未转化数据："+json);
		json = URLDecoder.decode(json,"utf-8");
		String[] s = json.split("=");
		if(s.length>1){
			json = s[1];
		}
		System.out.println("已转化数据："+json);
		//判断是否 正常传值
		if(json.isEmpty()){
			//0表示失败；1表示成功
			returnValue = false;
		}else{
			if(json.indexOf("[")==-1){
				json = "["+json;
			}
			if(json.indexOf("]")==-1){
				json = json+"]";
			}
			List<SonkaData> list = gDataService.returnDataByMobile(json);
			for(SonkaData sData : list){
				//获取用户基本数据
				BaseInfo baseInfo = gDataService.returnObject(sData, BaseInfo.class, 1);
				//获取脂肪信息
				HealthFat hFat = gDataService.returnObject(sData, HealthFat.class, 2);
				//获取血压信息
				HealthPressure hPressure = gDataService.returnObject(sData, HealthPressure.class, 3);
				//获取血糖信息
				HealthSugar hSugar = gDataService.returnObject(sData, HealthSugar.class, 4);
				//获取体重
				HealthWeight hweight = gDataService.returnObject(sData, HealthWeight.class, 5);
				//获取血氧
				HealthBlood hBlood = gDataService.returnObject(sData, HealthBlood.class, 6);
				//获取心电
				HealthLink hLink = gDataService.returnObject(sData, HealthLink.class, 7);
				//获取心电图
				Electrocardio ecg = gDataService.returnObject(sData, Electrocardio.class, 8);
				//获取体温
				Temperature temperature = gDataService.returnObject(sData, Temperature.class, 9);
				//获取尿常规
				Urine urine = gDataService.returnObject(sData, Urine.class, 10);
				//报表
				ColligateReport cReport = gDataService.returnObject(sData, ColligateReport.class, 11);
				bl =  saveData(baseInfo, hFat, hPressure, hSugar, hweight, hBlood, hLink, ecg, temperature,urine,cReport);
				
				if(bl){
					returnValue = true;
				}
			}
		}
		return returnValue;
	}
	
	public Boolean saveData(BaseInfo baseInfo,HealthFat hFat,HealthPressure hPressure,
			HealthSugar hSugar,HealthWeight hweight,HealthBlood hBlood,HealthLink hLink,
			Electrocardio ecg, Temperature temperature,Urine u,ColligateReport cReport){
		Boolean b = false;
		//获取身份号
		String idCard = baseInfo.getIdCardCode();
		if(!ValidatorUtil.isBlankOnString(idCard)){
			BaseInfo bInfo = new BaseInfo();
			//根据身份号查询
			List<BaseInfo> bList = bInfoService.select(idCard);
			//查找是否存在用户档案
			if (bList.size()==0) {
				String userCode = idCard.substring(0, 6);
				int maxId = bInfoService.maxId(userCode);
				String str = GlobalConstant.baseidPrefix + StringUtil.formatString(5, maxId);
				int random=(int)(Math.random()*1000000);
				//设置persongId
				baseInfo.setPersonId(baseInfo.getPersonId());
				if(ValidatorUtil.isBlankOnString(baseInfo.getPersonId())){
					//设置persongId
					baseInfo.setPersonId(userCode+"00"+str);
					baseInfo.setCheckCardId("");
				}
				//为用户自动建档
				bInfoService.insert(baseInfo); 
				switch (GlobalConstant.systemType) {
				case 0:
					personId = baseInfo.getId()+"";
					break;
				case 1:
					personId = baseInfo.getPersonId();
					break;
				default:
					break;
				}
				
			}else {
				switch (GlobalConstant.systemType) {
				case 0:
					personId = bList.get(0).getId()+"";
					break;
				case 1:
					personId = bList.get(0).getPersonId();
					break;
				default:
					break;
				}
				
			}
			
			if(!ValidatorUtil.isBlankOnString(hBlood.getSpo2())){
				//插入血氧
				hBlood.setPersonId(personId);//保存到health_blood
				if(GlobalConstant.systemType==1){
					hBlood.setCount(cService.getCount("count",personId, "yh_blood_oxygen"));//保存服务次数
				}
				hBloodService.insertHealthBlood(hBlood);
			}
			
			if(!ValidatorUtil.isNullOnDouble(hFat.getFat())||!ValidatorUtil.isNullOnDouble(hFat.getFatRate())){
				//插入脂肪信息
				hFat.setPersonId(personId.toString());//保存到health_fat
				if(GlobalConstant.systemType==1){
					hFat.setCounter(cService.getCount("counter", personId, "yh_blood_fat"));
				}
				hFat.setNext_serviceDate(StringUtil.getNextTime(hFat.getMeterDate(), 3));
				if(!ValidatorUtil.isNullOnDouble(hFat.getBmi())){
					hFat.setHealthBulld(StringUtil.weightState(hFat.getBmi()>0?hFat.getBmi():24));
				}
				hFatService.insertHealthFat(hFat);
			}
			
			if(!ValidatorUtil.isNullOnDouble(hPressure.getScDbpNow())&&!ValidatorUtil.isNullOnDouble(hPressure.getScSbpNow())){
				//插入血压信息
				hPressure.setPersonId(personId);//保存到blood_pressure
				if(GlobalConstant.systemType==1){
					hPressure.setCount(cService.getCount("count", personId, "yh_blood_pressure"));
				}
				hPressure.setNext_serviceDate(StringUtil.getNextTime(GlobalConstant.sdf.format(hPressure.getCreateDate()), 3));
				hPressure.setR_sbp(hPressure.getScDbpNow());
				hPressure.setR_dbp(hPressure.getScSbpNow());
				hPressure.setPressureState(Pressure.evaluation(hPressure.getScDbpNow(), hPressure.getScSbpNow())+"");
				hPressureService.insertHealthPressure(hPressure);
			}
			
			if((!ValidatorUtil.isNullOnDouble(hSugar.getFbg()))||!ValidatorUtil.isNullOnDouble(hSugar.getOgtt())||!ValidatorUtil.isNullOnDouble(hSugar.getGlu())){
				//插入血糖信息
				hSugar.setPersonId(personId);//保存到health_sugar
				if(GlobalConstant.systemType==1){
					hSugar.setCounter(cService.getCount("count", personId, "yh_blood_sugar"));
				}else hSugar.setCounter(hSugarService.getCounter(personId)+1);
				hSugar.setNext_serviceDate(StringUtil.getNextTime(hSugar.getMeterDate(), 3));
				if(ValidatorUtil.isNullOnDouble(hSugar.getOgtt())){
					hSugar.setOgtt(hSugar.getFbg());
				}
				hSugar.setSugarState(Sugar.sugarState(hSugar.getFbg(), hSugar.getOgtt())+"");
				hSugarService.insertHealthSugar(hSugar);
			}
			
			if(!ValidatorUtil.isNullOnDouble(hweight.getWeight())&&!ValidatorUtil.isNullOnDouble(hweight.getHeight())){
				//插入体重
				hweight.setPerson_id(personId);//保存到health_weight
				if(GlobalConstant.systemType==1){
					hweight.setCount(cService.getCount("count", personId, "yh_weight_height"));
				}
				hWeightService.insertHealthWeight(hweight);
			}
			
			if(GlobalConstant.systemType == 0){
				if(!ValidatorUtil.isBlankOnString(hLink.getHeartRhythm())){
					//插入心电
					hLink.setIdNo(personId);
					hLinkService.insertHealthLink(hLink);
				}
			}
			
			if(!ValidatorUtil.isNullOnString(ecg.getHeaterate())){
				//插入心电图
				ecg.setPersonId(personId.toString());
				ecg.setReportPath("");
				if(GlobalConstant.systemType==1){
					ecg.setCount(cService.getCount("count", personId, "yh_electrocardio"));
				}
				eService.insertElectrocardio(ecg);
			}
			
			if(!ValidatorUtil.isNullOnDouble(temperature.getTemperature())){
				//插入体温
				temperature.setPersonId(personId.toString());
				if(GlobalConstant.systemType==1){
					temperature.setCount(cService.getCount("count", personId, "yh_temperature"));
				}
				tService.insetTemperature(temperature);
			}
			
			if(!ValidatorUtil.isBlankOnString(u.getAgreement())){
				//插入尿常规
				u.setPersonId(personId);
				u = usi.saveUrine(u);
			}
			
			//保存报表数据
			if(!ValidatorUtil.isBlankOnString(cReport.getCreateMan())){
				cReport.setPersonId(personId);
				crs.insertColligateReport(cReport);
			}
			b = true;
		}
		return b;
	}
	
	/**
	 * 双佳一体机接口2.0 (SK-E100)
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getE100Data.do")
	@ResponseBody
	public Json getE100Data(HttpServletRequest request) throws Exception{
		Json j = new Json();
		request.setCharacterEncoding("utf-8");
		//获取request传输过来的字符流
		BufferedReader bf = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line;
		//循环读取字符流所有字符添加到 sb可变字符串
		while((line=bf.readLine())!=null){
			sb.append(line);
		}
		String json = sb.toString();
		System.out.println("未转化数据："+json);
		//乱码处理
		json = new String(json.getBytes("iso-8859-1"),"utf-8");
		String[] s = json.split("=");
		if(s.length>1){
			json = s[1];
		}
		json = URLDecoder.decode(json,"utf-8");
		System.out.println("已转化数据："+json);
		//判断是否 正常传值
		if(json.isEmpty()){
			j.setSuccess(false);
			j.setMessage("信息数据为空");
			return j ;
		}else{
			E100AllData ead = gDataService.getE100AllData(json);
			//获取用户基本数据
			BaseInfo baseInfo = gDataService.returnE100Data(ead, BaseInfo.class, 1);
			if(baseInfo!=null){
				ead.setBranchno(ValidatorUtil.isBlankOnString(baseInfo.getCreatfileDepId())?"":baseInfo.getCreatfileDepId());
			}
			//获取脂肪信息
			HealthFat hFat = gDataService.returnE100Data(ead, HealthFat.class, 2);
			//获取血压信息
			HealthPressure hPressure = gDataService.returnE100Data(ead, HealthPressure.class, 3);
			//获取血糖信息
			HealthSugar hSugar = gDataService.returnE100Data(ead, HealthSugar.class, 4);
			//获取体重
			HealthWeight hweight = gDataService.returnE100Data(ead, HealthWeight.class, 5);
			//获取血氧
			HealthBlood hBlood = gDataService.returnE100Data(ead, HealthBlood.class, 6);
			//获取心电
			HealthLink hLink = gDataService.returnE100Data(ead, HealthLink.class, 7);
			//心电图
			Electrocardio ecg = gDataService.returnE100Data(ead, Electrocardio.class, 8);
			//体温
			Temperature temperature = gDataService.returnE100Data(ead, Temperature.class, 9);
			//报表
			ColligateReport cReport = gDataService.returnE100Data(ead, ColligateReport.class, 10);
			
			if(!ValidatorUtil.isBlankOnString(ead.getIdCode())){
				bl = saveData(baseInfo, hFat, hPressure, hSugar, hweight, hBlood, hLink, ecg, temperature,new Urine(),new ColligateReport());
				//保存信息到数据库
				sds.insertSkData(personId,json);
				//保存报表数据
				if(cReport!=null){
					cReport.setPersonId(personId);
					crs.insertColligateReport(cReport);
				}
			}
			if(bl){
				j.setMessage("上传成功");
				j.setSuccess(true);
			}else{
				j.setMessage("上传失败");
				j.setSuccess(false);
			}
			
		}
		return j;
	}
}
